package protocols.JobProtocol;

import job.Job;
import job.JobEnvelope;
import peer.Connection;
import peer.Message;
import protocols.Protocol;
import protocols.ProtocolState;
import protocols.joinProtocol.JoinProtocol.States;

public class JobProtocol<T extends Enum<?>, S extends Enum<?>> extends Protocol<T,S>{
	public static final String NAME = "JobProtocol";
		public String getName() {	return NAME;	}
	public enum States {accepting, overloaded};
	public enum MessageTypes {job, request, result};
	
	private States state;
	
	protected JobProtocol(Connection _conn) {
		super(_conn);		
		addHandler((S)States.accepting, new AcceptingState());
		addHandler((S)States.overloaded, new OverloadedState());
		this.setState((S)States.accepting);	
	}
	
	public static JobProtocol<MessageTypes,States> monitor(Connection conn) {		
		JobProtocol<MessageTypes,States> protocol = new JobProtocol<MessageTypes,States>(conn);
		conn.registerProtocol(NAME, protocol);
		System.out.println("\thow about inside " + NAME + ": " + (protocol.callback == null));
		new Thread(protocol).start();
		
		return null;
		
	}
	
	private class AcceptingState extends ProtocolState<S> {

		@Override
		public void handle(Message packet, Connection conn) {
			if (callback.isLeader()) {
				if (MessageTypes.valueOf(packet.type) == MessageTypes.request) {
					try {
						callback.addJob((JobEnvelope)packet.data);						
					} catch (ClassCastException e) {
						System.err.println("BAD MESSAGE CONTENTS. ITS THE END OF THE WORLD");
					}
				}
			} else if (MessageTypes.valueOf(packet.type) == MessageTypes.job) {
				try {
					callback.addJob((JobEnvelope)packet.data);
				} catch (ClassCastException e) {
					System.err.println("BAD MESSAGE CONTENTS. ITS THE END OF THE WORLD");
				}
			}
		}
		
	}
	
	private class OverloadedState extends ProtocolState<S> {

		@Override
		public void handle(Message packet, Connection conn) {
			System.out.println("Im overloaded. Fuck off asshole.");
			
		}
		
	}

	
	

}
